package com.jiazhong.spring.ioc.mybatis.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiazhong.commons.bean.Emp;
import com.jiazhong.commons.util.JsonResult;
import com.jiazhong.commons.util.ResultTool;
import com.jiazhong.spring.ioc.mybatis.mapper.EmpMapper;
import com.jiazhong.spring.ioc.mybatis.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {

    private EmpMapper empMapper;

    @Autowired
    public EmpServiceImpl(EmpMapper empMapper) {
        this.empMapper = empMapper;
    }

    @Override
    public JsonResult findAll() {
        List<Emp> list = empMapper.findAll();
        if (list == null || list.isEmpty()) {
            return ResultTool.fail(500, "查询数据失败");
        }
        return ResultTool.success(list);
    }

    @Override
    public JsonResult findByPage(int page, int size) {
        PageHelper.startPage(page, size);
        List<Emp> list = empMapper.findAll();
        PageInfo<Emp> pageInfo = new PageInfo<>(list);
        return ResultTool.success(pageInfo);
    }

    @Override
    public JsonResult findByEname(String ename) {
        if (ename == null) {
            return ResultTool.fail(500, "必须携带查询条件");
        }
        List<Emp> list = empMapper.findByEname("%" + ename + "%");
        return ResultTool.success(list);
    }

    @Override
    public JsonResult findById(int id) {
        return ResultTool.success(empMapper.findById(id));
    }

    @Override
    public JsonResult saveOrUpdate(Emp emp) {
        if (emp.getEmpNo() == null) {
            int row = empMapper.save(emp);
            if (row == 0) {
                return ResultTool.fail(500, "添加失败");
            }
            return ResultTool.success("success");
        }
        int row = empMapper.update(emp);
        if (row == 0) {
            return ResultTool.fail(500, "修改失败");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult removeById(int id) {
        int row = empMapper.removeById(id);
        if (row == 0) {
            return ResultTool.fail(500, "删除失败");
        }
        return ResultTool.success("success");
    }
}
